<template>
  <div class="app-container" v-loading="pageLoading">
    <el-button type="primary" class="fr" @click="createItem" v-permission="'material.add'">创建</el-button>
    <div class="filter-container">
      <el-input style="width: 260px;" placeholder="输入备件料号" clearable class="filter-item" @keyup.enter.native="research"
        @clear="research" v-model="query.item_no">
      </el-input>
      <el-input style="width: 260px;" placeholder="输入备件名称" clearable class="filter-item" @keyup.enter.native="research"
        @clear="research" v-model="query.name">
      </el-input>
      <el-button class="filter-item" type="success" plain @click="research">查询</el-button>
      <el-button class="filter-item" type="info" plain @click="exportData" :loading="exportLoading">导出 </el-button>
    </div>
    <z-table :list="list" :tableProps="tableProps" :columns="columns" @editItem="editItem" @deleteItem="deleteItem">
      <template v-slot:content="v">
        <span v-if="v.key == 'status'"
          :class="[v.row['actual_stock'] > v.row['safe_stock']?'text-label bg-green':'text-label bg-yellow']">
          {{v.row['actual_stock'] > v.row['safe_stock'] ? '正常':'缺少'}}
        </span>
        <span v-else>{{ v.row[v.key] }}</span>
      </template>
      <template v-slot:operation='v'>
        <a href="javascript:;" class="text-green" @click="getDetailed(v.row)">明细</a>
        <a href="javascript:;" class="text-green" @click.stop="attachmentRetrieval(v,0)">备件入库</a>
        <a href="javascript:;" class="text-yellow" @click.stop="attachmentRetrieval(v,1)">备件出库</a>
        <a href="javascript:;" class="text-blue" @click.stop="editItem(v.row)">编辑</a>
        <a style="margin-left:5px;" href="javascript:;" class="text-red" @click.stop="deleteItem(v.row)">删除</a>
      </template>
    </z-table>
    <z-pagination :pagination="pagination" :total="total" :page.sync="query.page" :limit.sync="query.size"
      @change="getList"></z-pagination>
    <z-form-dialog :name="name" :data="data" :formProps="formProps" :fields="fields" @submit="submit"
      :submitLoading="submitLoading" :visible.sync="editFormVisible"></z-form-dialog>

    <!-- 备件出库/入库 -->
    <z-form-dialog :data="entryAndOutData" :formProps="entryAndOutformProps" :fields="entryAndOutfields"
      @submit="entryAndOutsubmit" :submitLoading="submitLoading" :visible.sync="attachmentRetrievalShow"
      :before-close="beforeClose">
      <template v-slot:extra-area v-if="partRetrievalShow">
        <div style="width:95%;margin-left:5%;margin-bottom:15px">
          <z-table :list="partRetrievalList" :tableProps="partRetrievalTableProps" :columns="partRetrievalColumns">
            <template v-slot:content="v">
              <span v-if="v.key == 'number'">
                <template>
                  <el-input-number v-model="v.row['number']" @change="handleChange" :min="0" :disabled="!numberAdd"
                    :max="v.row['qty']" label="描述文字">
                  </el-input-number>
                </template>
              </span>
              <span v-else>{{ v.row[v.key] }}</span>
            </template>
          </z-table>
        </div>
      </template>
      <template v-slot:footer>
        <el-button @click="beforeClose()">取消</el-button>
        <el-button type="primary" @click.native="entryAndOutsubmit()" :loading="submitLoading">确认
        </el-button>
      </template>
    </z-form-dialog>
    <!-- 明细账 subsidiaryLedger -->
    <el-dialog title="备件明细账" :visible.sync="subsidiaryLedgerShow" width="60%" :before-close="setparentShow"
      append-to-body>
      <el-tabs v-model="activeName">
        <el-tab-pane label="明细账" name="subLedger">
          <subLedger :activeName="activeName" :DetailedItemNo="DetailedItemNo">用户管理</subLedger>
        </el-tab-pane>
        <el-tab-pane label="异动日志" name="changeLog">
          <changeLog :activeName="activeName" :DetailedItemNo="DetailedItemNo">配置管理</changeLog>
        </el-tab-pane>
      </el-tabs>
    </el-dialog>
  </div>
</template>
<script>
import commonMixin from '@/views/_common/mixin'
import subLedger from '@/views/tpm/partManage/components/subLedger'
import changeLog from '@/views/tpm/partManage/components/changeLog'
export default {
  name: 'partsAccount',
  mixins: [commonMixin],
  components: { subLedger, changeLog },
  props: {},
  data() {
    return {
      query: {
        page: 1,
        size: 10,
      },
      api: this.$api.TpmPartAccount,
      baseUrl: this.$api.baseUrl,
      postForList: true,
      name: '备件',
      tableProps: {
        border: true,
        opsColWith: 280,
        fixed: false,

        hideOperations: false,
      },
      personnelOptions: [],
      activeName: 'subLedger',
      DetailedItemNo: '',
      columns: [
        { title: '备件料号', key: 'item_no', width: 100, fixed: 'left' },
        { title: '备件名称', key: 'name', width: 100 },
        { title: '备件规格型号', key: 'specifications', width: 140 },
        { title: '存放位置', key: 'place' },
        { title: '安全库存', key: 'safe_stock', width: 100 },
        { title: '实际库存', key: 'actual_stock', width: 100 },
        { title: '采购周期', key: 'period' },
        { title: '保管人', key: 'custodian', width: 120 },
        { title: '状态', key: 'status', width: 80 },
        { title: '修改人', key: 'modify_user', width: 100 },
        { title: '最后修改时间', key: 'modify_time', width: 140 },
      ],
      fields: [
        { title: '备件料号', key: 'item_no', span: 12 },
        { title: '备件名称', key: 'name', span: 12 },
        {
          title: '备件规格型号',
          key: 'specifications',
          span: 12,
        },
        { title: '存放位置', key: 'place', span: 12, required: true },
        { title: '安全库存', key: 'safe_stock', span: 12, name: 'number', required: true },
        { title: '实际库存', key: 'actual_stock', span: 12, name: 'number', required: true },
        { title: '采购周期', key: 'period', span: 12 },
        {
          title: '保管人',
          key: 'custodian',
          span: 12,
          name: 'select',
          options: [],
          props: { filterable: true, remote: true, clearable: true, 'remote-method': this.getpersonnel },
        },
      ],

      // 报废弹框
      scrapDialog: false,
      // 备件出库/入库
      attachmentRetrievalShow: false,
      entryAndOutData: {
        item_no: '',
        specifications: '',
        place: '',
        maxQty: '',
      },
      entryAndOutformProps: {
        dialogWidth: '70%',
        labelWidth: '140px',
        title: '出库',
      },
      entryAndOutfields: [],
      subsidiaryLedgerShow: false,
      // 出库table
      partRetrievalList: [],
      partRetrievalTableProps: {
        border: true,
        fixed: false,
        hideOperations: true,
      },
      partRetrievalColumns: [
        { title: '备件编号', key: 'serial_number' },
        { title: '仓库数量', key: 'qty' },
        { title: '出库数量', key: 'number', width: 200, hideTooltip: true },
      ],
      partRetrievalShow: false,
      numberAdd: true,
    }
  },
  computed: {},
  watch: {},
  created() {
    this.research()
    this.getpersonnel()
  },
  mounted() {},
  methods: {
    getDetailed(val) {
      this.subsidiaryLedgerShow = true
      this.DetailedItemNo = val.item_no
    },
    // 获取人员
    getpersonnel(val) {
      let Params = {
        queryString: val ? val : '',
        page: 1,
        size: 100,
      }
      this.$request(this.baseUrl + 'platform/user/getList', Params).then((r) => {
        const { list } = r
        this.personnelOptions = list.map((i) => ({
          label: `${i.userid} ${i.username}`,
          value: i.userid,
        }))
        this.getFieldConfig('custodian').options = this.personnelOptions
      })
    },
    submit() {
      this.submitLoading = true
      this.$request(this.api + 'add', this.data, 'post')
        .then((r) => {
          this.$message.success('操作成功')
          this.editFormVisible = false
          this.getList()
        })
        .finally(() => {
          this.submitLoading = false
        })
    },
    // 出库/入库按钮弹框
    attachmentRetrieval(v, type) {
      if (type) {
        this.partRetrievalShow = true
        this.entryAndOutData.item_no = v.row.item_no
        this.getOutNO()
        this.entryAndOutfields = [
          {
            title: '出库申请单',
            key: 'change_order',
            span: 12,
            name: 'select',
            options: [],
            required: true,
            props: { filterable: true, remote: true, clearable: true, 'remote-method': this.getOutNO },
            events: {
              change: this.setDetails,
            },
          },
          {
            title: '应出数量',
            key: 'maxQty',
            span: 12,
            props: {
              disabled: true,
            },
          },
          {
            title: '备件料号',
            key: 'item_no',
            span: 12,
            props: {
              disabled: true,
            },
          },
          { title: '备注', key: 'remarks', span: 24, name: 'textarea' },
        ]
        this.entryAndOutformProps.title = '出库'
      } else {
        this.putPart(v)
        this.entryAndOutfields = [
          {
            title: '入库类型',
            key: 'change_type',
            span: 12,
            name: 'radio',
            required: true,
            options: [
              { label: '采购入库', value: 0 },
              { label: '退回入库', value: 1 },
            ],
          },
          {
            title: '备件分类',
            key: 'key_part_type',
            span: 12,
            name: 'radio',
            required: true,
            options: [
              { label: '单件', value: 1 },
              { label: '批件', value: 2 },
            ],
            events: {
              change: this.editNumber,
            },
          },

          {
            title: '备件料号',
            key: 'item_no',
            span: 12,
            props: {
              disabled: true,
            },
          },
          {
            title: '备件规格型号',
            key: 'specifications',
            span: 12,
            props: {
              disabled: true,
            },
          },
          {
            title: '备件位置',
            key: 'place',
            span: 12,
            props: {
              disabled: true,
            },
          },
          {
            title: '数量',
            key: 'qty',
            span: 12,
            name: 'number',
            props: {
              min: 0,
            },
          },
        ]
        this.entryAndOutformProps.title = '入库'
      }
      this.attachmentRetrievalShow = true
    },
    editNumber() {
      if (this.entryAndOutData.key_part_type == 1) {
        this.entryAndOutData.qty = 1
        this.setFieldsDisable(true, 'qty', this.entryAndOutfields)
      } else {
        this.entryAndOutData.qty = undefined
        this.setFieldsDisable(false, 'qty', this.entryAndOutfields)
      }
    },
    // 入库
    putPart(val) {
      const { row } = val
      let url = this.api + 'getbyid'
      this.$request(url, {
        id: row.id,
      }).then((r) => {
        this.entryAndOutData.item_no = r.item_no
        this.entryAndOutData.specifications = r.specifications
        this.entryAndOutData.place = r.place
      })
    },

    // 出库/入库确认按钮
    entryAndOutsubmit() {
      if (this.partRetrievalShow) {
        // 出库
        let tmp = []
        this.partRetrievalList.forEach((i) => {
          if (i.number) {
            let obj = {
              serial_number: i.serial_number,
              qty: i.number,
            }
            tmp.push(obj)
          }
        })
        this.entryAndOutData.items = tmp
        let Data = {
          ...this.entryAndOutData,
        }
        let check = this.validataData(this.entryAndOutfields, this.entryAndOutData)
        if (!check) return
        this.submitLoading = true
        this.$request(this.api + 'PartReceive', Data, 'post')
          .then((r) => {
            this.$message.success('出库成功')
            this.beforeClose()
          })
          .finally(() => {
            this.submitLoading = false
          })
      } else {
        // 入库
        let Data = {
          ...this.entryAndOutData,
        }
        let check = this.validataData(this.entryAndOutfields, this.entryAndOutData)
        if (!check) return
        this.submitLoading = true
        this.$request(this.api + 'PartWarehousing', Data, 'post')
          .then((r) => {
            this.$message.success('入库成功')
            this.beforeClose()
          })
          .finally(() => {
            this.submitLoading = false
          })
      }
    },

    // 控制父级关闭弹框
    setparentShow() {
      this.subsidiaryLedgerShow = false
      // this.$parent.subsidiaryLedgerShow = false
    },
    // 远程搜索
    getOutNO(val) {
      let Data = {
        item_no: this.entryAndOutData.item_no,
        order_number: val ? val : '',
        page: 1,
        size: 100,
      }
      this.$request(this.baseUrl + 'Tpm/TpmPartReceive/GetTpmPartReceive', Data, 'post').then((r) => {
        const { list } = r
        let tmp = list.map((i) => ({
          label: i.order_number,
          value: i.order_number,
        }))
        let fieldItem = this.entryAndOutfields.find((i) => i.key == 'change_order')
        fieldItem.options = tmp
      })
    },
    handleChange(value) {
      let number = null
      this.partRetrievalList.forEach((i) => {
        if (i.number) {
          number += i.number
        }
      })
      if (this.entryAndOutData.maxQty <= number) {
        this.numberAdd = false
      }
    },
    setDetails(val) {
      this.entryAndOutData.maxQty = null
      this.numberAdd = true
      if (!val) return

      let Data = {
        order_number: val ? val : '',
        page: 1,
        size: 100,
      }
      this.$request(this.baseUrl + 'Tpm/TpmPartReceive/GetTpmPartReceive', Data, 'post').then((r) => {
        const { list } = r

        this.entryAndOutData.maxQty = list[0].qty
        let data = {
          item_no: this.entryAndOutData.item_no,
          isall: false,
          page: 1,
          size: 100,
        }
        this.$request(this.api + 'GetPartDetailList', data, 'post').then((r) => {
          const { list } = r
          list.forEach((i) => {
            i.number = undefined
          })
          this.partRetrievalList = list
        })
      })
    },
    // 关闭出库/入库
    beforeClose() {
      this.attachmentRetrievalShow = false
      this.partRetrievalShow = false
      this.entryAndOutData = {
        item_no: '',
        specifications: '',
        place: '',
        maxQty: '',
      }
      this.partRetrievalList = []
      this.numberAdd = true
    },
  },
}
</script>

<style lang="scss" scoped>
.icon-class {
  font-size: 18px;
  cursor: pointer;
}
.dialog-padding ::v-deep .el-dialog__body {
  padding: 30px 20px 50px;
  color: #606266;
  font-size: 14px;
  word-break: break-all;
}
</style>